﻿using NFine.Code;
using NFine.Domain.Entity.SystemManage;
using NFine.Domain.Entity.BusinessManage;
using NFine.Domain.IRepository.SystemManage;
using NFine.Repository.SystemManage;
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace NFine.Application.SystemManage
{
    public class UserApp
    {
        private IUserRepository service = new UserRepository();
        private UserLogOnApp userLogOnApp = new UserLogOnApp();

        public List<UserEntity> GetList(Pagination pagination, string keyword)
        {
            var expression = ExtLinq.True<UserEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.F_Account.Contains(keyword));
                expression = expression.Or(t => t.F_RealName.Contains(keyword));
                expression = expression.Or(t => t.F_MobilePhone.Contains(keyword));
            }
            expression = expression.And(t => t.F_Account != "admin");
            expression = expression.And(t => t.F_Installed == false);
            return service.FindList(expression, pagination);
        }

        public List<UserEntity> GetMembersList(Pagination pagination, string keyword)
        {
            var model = new UserEntity();
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                model = JsonConvert.DeserializeObject<UserEntity>(keyword);
            }
            var expression = ExtLinq.True<UserEntity>();
            expression = expression.And(t => t.F_IsAdministrator == false);
            expression = expression.And(t => t.F_Account != "admin");
            if (!string.IsNullOrEmpty(model.F_Account))
            {
                expression = expression.And(t => t.F_Account.Contains(model.F_Account));
            }
            if (!string.IsNullOrEmpty(model.F_RealName))
            {
                expression = expression.And(t => t.F_RealName.Contains(model.F_RealName));
            }
            return service.GetMembersList(expression, pagination);
        }

        public List<UserEntity> GetAllMemberAccount(string keyAccount, string keyRealName)
        {
            var expression = ExtLinq.True<UserEntity>();
            expression = expression.And(t => t.F_IsAdministrator == false);
            expression = expression.And(t => t.F_Account != "admin");
            if (!string.IsNullOrEmpty(keyAccount))
            {
                expression = expression.And(t => t.F_Account.Contains(keyAccount));
            }
            if (!string.IsNullOrEmpty(keyRealName))
            {
                expression = expression.And(t => t.F_RealName.Contains(keyRealName));
            }
            return service.GetMembersList(expression);
        }

        public UserEntity GetForm(string keyValue)
        {
            return service.GetForm(keyValue);
        }
        public D_SalaryEntity GetAmcount(string keyValue)
        {
            return service.GetAmcount(keyValue);
        }

        public void DeleteForm(string keyValue)
        {
            service.DeleteForm(keyValue);
        }
        public void SubmitForm(UserEntity userEntity, UserLogOnEntity userLogOnEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                userEntity.Modify(keyValue);
            }
            else
            {
                var expression = ExtLinq.True<UserEntity>();
                expression = expression.And(t => t.F_Account == userEntity.F_Account);
                int count = service.FindListCount(expression);
                if (count > 0)
                {
                    throw new Exception("账号名重复，不能新增");
                }
                userEntity.Create();
            }
            service.SubmitForm(userEntity, userLogOnEntity, keyValue);
        }

        public void SubmitRePassword(string type, string old, string newpass)
        {
            service.SubmitRePassword(type, old, newpass);
        }

        public void SubmitMember(UserEntity userEntity, string keyValue)
        {
            service.SubmitMember(userEntity, keyValue);
        }

        public void SubTransfer(UserEntity userEntity)
        {
            service.SubTransfer(userEntity);
        }

        public void Recharge(UserEntity userEntity)
        {
            service.Recharge(userEntity);
        }

        public void FRecharge(UserEntity userEntity)
        {
            service.FRecharge(userEntity);
        }

        public void SubmitMemberForm(UserEntity userEntity, UserLogOnEntity userLogOnEntity, string GoodIds, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                userEntity.Modify(keyValue);
            }
            else
            {
                var expression = ExtLinq.True<UserEntity>();
                expression = expression.And(t => t.F_Account == userEntity.F_Account);
                int count = service.FindListCount(expression);
                if (count > 0)
                {
                    throw new Exception("账号名重复，不能新增");
                }
                userEntity.Create();
            }

            var currentUser = OperatorProvider.Provider.GetCurrent();
            userEntity.ReferenceID = currentUser.UserId;
            if (currentUser.IsMember)   //会员注册
                service.RegisterNewUserCore(userEntity, userLogOnEntity, GoodIds);
            else                        //管理员注册第一个人
                service.RegisterFirstUser(userEntity, userLogOnEntity, GoodIds);
        }
        public void UpdateForm(UserEntity userEntity)
        {
            service.Update(userEntity);
        }
        public UserEntity CheckLogin(string username, string password)
        {
            UserEntity userEntity = service.FindEntity(t => t.F_Account == username);
            if (userEntity != null)
            {
                if (userEntity.F_EnabledMark == true)
                {
                    UserLogOnEntity userLogOnEntity = userLogOnApp.GetForm(userEntity.F_Id);
                    string dbPassword = Md5.md5(DESEncrypt.Encrypt(password.ToLower(), userLogOnEntity.F_UserSecretkey).ToLower(), 32).ToLower();
                    if (dbPassword == userLogOnEntity.F_UserPassword)
                    {
                        DateTime lastVisitTime = DateTime.Now;
                        int LogOnCount = (userLogOnEntity.F_LogOnCount).ToInt() + 1;
                        if (userLogOnEntity.F_LastVisitTime != null)
                        {
                            userLogOnEntity.F_PreviousVisitTime = userLogOnEntity.F_LastVisitTime.ToDate();
                        }
                        userLogOnEntity.F_LastVisitTime = lastVisitTime;
                        userLogOnEntity.F_LogOnCount = LogOnCount;
                        userLogOnApp.UpdateForm(userLogOnEntity);
                        return userEntity;
                    }
                    else
                    {
                        throw new Exception("密码不正确，请重新输入");
                    }
                }
                else
                {
                    throw new Exception("账户被系统锁定,请联系管理员");
                }
            }
            else
            {
                throw new Exception("账户不存在，请重新输入");
            }
        }

        public List<D_SalaryHistoryEntity> GetUserSalary(Pagination pagination, string keyword)
        {
            var expression = ExtLinq.True<D_SalaryHistoryEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.Account.Contains(keyword));
                expression = expression.Or(t => t.AccountName.Contains(keyword));
                expression = expression.Or(t => t.TAccountName.Contains(keyword));
            }
            var userId = OperatorProvider.Provider.GetCurrent().UserId;
            return service.GetUserSalary(userId, expression, pagination);
        }

        public List<D_AccountEntity> GetCompanyAccount(Pagination pagination, string keyword, string beginTime, string endTime,string ChangeType, string IsIncome)
        {
            var expression = ExtLinq.True<D_AccountEntity>();
            if (!string.IsNullOrEmpty(beginTime))
            {
                DateTime begin = beginTime.ToDate();
                expression = expression.And(t => t.TriggerTime >= begin);
            }            
            if (!string.IsNullOrEmpty(endTime))
            {
                DateTime end = endTime.ToDate();
                expression = expression.And(t => t.TriggerTime <= end);
            }
            if (!string.IsNullOrEmpty(ChangeType))
            {
                expression = expression.And(t=>t.ChangeType.Equals(ChangeType));
            }
            if (!string.IsNullOrEmpty(IsIncome))
            {
                bool a = Convert.ToBoolean(IsIncome.ToInt());
                expression = expression.And(t => t.IsIncome==a);
            }
            var expression1 = ExtLinq.True<UserEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression1 = expression1.And(t => t.F_Account.Contains(keyword));
            }
            return service.GetCompanyAccount(expression,expression1, pagination);
        }

        public List<D_AccountEntity> GetCompanyAccount(string keyword, string beginTime, string endTime, string ChangeType, string IsIncome)
        {
            var expression = ExtLinq.True<D_AccountEntity>();
            if (!string.IsNullOrEmpty(beginTime))
            {
                DateTime begin = beginTime.ToDate();
                expression = expression.And(t => t.TriggerTime >= begin);
            }
            if (!string.IsNullOrEmpty(endTime))
            {
                DateTime end = endTime.ToDate();
                expression = expression.And(t => t.TriggerTime <= end);
            }
            if (!string.IsNullOrEmpty(ChangeType))
            {
                expression = expression.And(t => t.ChangeType.Equals(ChangeType));
            }
            if (!string.IsNullOrEmpty(IsIncome))
            {
                bool a = Convert.ToBoolean(IsIncome.ToInt());
                expression = expression.And(t => t.IsIncome==a);
            }
            var expression1 = ExtLinq.True<UserEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression1 = expression1.And(t => t.F_Account.Contains(keyword));
                expression1 = expression1.Or(t => t.F_AccountName.Contains(keyword));
            }
            return service.GetCompanyAccount(expression, expression1);
        }

        public UserEntity GetAreas(string userId)
        {
            return service.GetAreas(userId);
        }

        public List<UserEntity> GetChilds(string userId)
        {
            return service.FindList("select * from sys_user where ReferenceID='"+ userId + "' order by F_CreatorTime asc");
        }

        public UserEntity FindEntityByFunc(Func<UserEntity, bool> predicate)
        {
            return service.FindEntityByFunc(predicate);
        }

        public UserEntity FindLastUserByCardid(string cardid)
        {
            return service.FindLastUserByCardid(cardid);
        }

        public UserEntity GetAllMemberFormJson(string keyValue)
        {
            return service.GetAllMemberFormJson(keyValue);
        }
    }
}
